<template>
	<div class="app-container">
		<el-header style="height:160px">
			<div class="container-top">
				<i class="el-icon-search" style="font-size:150px"></i>
				<div class="top-list">
					<p style="font-weight:900">平台版本信息</p>
					<div>
						<span>后台版本：{{platformInfo.backstageV}}</span>
					</div>
					<div>
						<span>JAVA版本：{{platformInfo.javaV}}</span>
					</div>
					<div>
						<span>发布时间：{{platformInfo.createTime}}</span>
					</div>
					<div>
						<span>更新时间：{{platformInfo.updateTime}}</span>
					</div>
				</div>
			</div>
		</el-header>
		<el-main>
			<el-form
				v-show="showSearch"
				ref="queryForm"
				:model="queryParams"
				:inline="true"
				label-width="68px"
			>
				<el-form-item label="版本名称" prop="name">
					<el-input
						v-model="queryParams.name"
						placeholder="请输入版本名称"
						clearable
						size="small"
						@keyup.enter.native="handleQuery"
					/>
				</el-form-item>
				<el-form-item label="版本类型" prop="type">
					<el-select
						v-model="queryParams.type"
						placeholder="请选择版本类型"
						clearable
						size="small"
					>
						<el-option
							v-for="dict in typeOptions"
							:key="dict.value"
							:label="dict.label"
							:value="dict.value"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-select
						v-model="queryParams.status"
						placeholder="请选择状态"
						clearable
						size="small"
					>
						<el-option
							v-for="dict in statusOptions"
							:key="dict.value"
							:label="dict.label"
							:value="dict.value"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="创建时间">
					<el-date-picker
						v-model="dateRange"
						size="small"
						style="width: 240px"
						value-format="yyyy-MM-dd"
						type="daterange"
						range-separator="-"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
					/>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						size="mini"
						@click="handleQuery"
						>搜索</el-button
					>
					<el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
						>重置</el-button
					>
				</el-form-item>
			</el-form>

			<el-row :gutter="10" class="mb8">
				<el-col :span="1.5">
					<el-button
						v-hasPerm="['version_add']"
						type="primary"
						icon="el-icon-plus"
						size="mini"
						@click="handleAdd"
						>新增</el-button
					>
				</el-col>
				<el-col :span="1.5">
					<el-button
						v-hasPerm="['version_edit']"
						type="success"
						icon="el-icon-edit"
						size="mini"
						:disabled="single"
						@click="handleEdit"
						>修改</el-button
					>
				</el-col>
				<el-col :span="1.5">
					<el-button
						v-hasPerm="['version_del']"
						type="danger"
						icon="el-icon-delete"
						size="mini"
						:disabled="multiple"
						@click="handleDel"
						>删除</el-button
					>
				</el-col>
				<!-- <el-col :span="1.5">
        <el-button
          v-hasPerm="['version_export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col> -->
				<div class="top-right-btn">
					<el-tooltip class="item" effect="dark" content="刷新" placement="top">
						<el-button
							size="mini"
							circle
							icon="el-icon-refresh"
							@click="handleQuery"
						/>
					</el-tooltip>
					<el-tooltip
						class="item"
						effect="dark"
						:content="showSearch ? '隐藏搜索' : '显示搜索'"
						placement="top"
					>
						<el-button
							size="mini"
							circle
							icon="el-icon-search"
							@click="showSearch = !showSearch"
						/>
					</el-tooltip>
				</div>
			</el-row>

			<el-table
				v-loading="loading"
				:data="versionList"
				@selection-change="handleSelectionChange"
				class="info-table"
			>
				<el-table-column type="selection" width="55" align="center" />
				<!--<el-table-column label="编号" align="center" prop="id" />-->
				<el-table-column label="版本名称" align="center" prop="name" />
				<el-table-column label="版本号" align="center" prop="code" width="80" />
				<el-table-column
					label="版本类型"
					align="center"
					prop="type"
					:formatter="typeFormat"
				/>
				<!--<el-table-column label="版本大小" align="center" prop="appSize" width="80" />-->
				<el-table-column label="状态" align="center" prop="status">
					<template slot-scope="scope">
						<el-tag v-if="scope.row.status === '2'" type="success">{{
							statusFormat(scope.row)
						}}</el-tag>
						<span v-else type="success">{{ statusFormat(scope.row) }}</span>
					</template>
				</el-table-column>
				<el-table-column
					label="版本说明"
					align="center"
					prop="describes"
					:show-overflow-tooltip="true"
				/>
				<el-table-column
					label="创建时间"
					align="center"
					prop="createTime"
					width="180"
				>
					<template slot-scope="scope">
						<span>{{ parseTime(scope.row.createTime) }}</span>
					</template>
				</el-table-column>
				<el-table-column
					width="200"
					label="操作"
					align="center"
					class-name="small-padding fixed-width"
					fixed="right"
				>
					<template slot-scope="scope">
						<!-- <el-button
							v-if="scope.row.status === '0'"
							size="mini"
							type="text"
							icon="el-icon-edit"
							@click="unZip(scope.row)"
							>解压</el-button
						> -->
						<el-button
							v-if="scope.row.status === '1'"
							size="mini"
							type="text"
							icon="el-icon-edit"
							@click="release(scope.row)"
							>使用</el-button
						>
						<!-- <el-button
							v-hasPerm="['version_edit']"
							size="mini"
							type="text"
							icon="el-icon-edit"
							@click="handleEdit(scope.row)"
							>修改</el-button
						> -->
						<el-button
							v-hasPerm="['version_del']"
							size="mini"
							type="text"
							icon="el-icon-delete"
							@click="handleDel(scope.row)"
							>删除</el-button
						>
					</template>
				</el-table-column>
			</el-table>
		</el-main>
		<el-footer>
			<pagination
				v-show="total > 0"
				:total="total"
				:page.sync="queryParams.current"
				:limit.sync="queryParams.size"
				@pagination="getList"
				style="margin:0"
			/>
		</el-footer>

		<!-- 添加或修改版本对话框 -->
		<!--apk  版本名称、报名号、app类型、版本说明、多行文本。 上传加上-->
		<!-- <el-dialog
    class="custom-dialog"
    :title="title"
    :visible.sync="open"
    :modal-append-to-body="true"
    :append-to-body="true"
    :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="版本名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入版本名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本号" prop="code">
              <el-input v-model="form.code" type="number" placeholder="请输入版本号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择版本类型">
                <el-option
                  v-for="dict in [{label:'java',value:'1'},{label:'后台页面',value:'2'}]"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文件上传">
              <el-upload
                ref="upload"
                class="upload-demo"
                drag
                :headers="{
                  Authorization: 'Bearer ' + getAccessToken()
                }"
                :action="`${VUE_APP_BASE_API}/common/uploadToFolder`"
                :on-success="handleOnSuccess"
                :on-error="handleOnError"
                multiple
              >
                <i class="el-icon-upload" />
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div v-if="form.url" slot="tip" class="el-upload__tip" style="font-size:16px">{{ form.fileName }}
                  <span v-if="successTitle" style="color:#67C23A;font-size:20px">【{{ successTitle }}】</span></div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="版本说明" prop="describes">
              <el-input v-model="form.describes" type="textarea" rows="3" placeholder="请输入版本说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="form.url===undefined" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog> -->
		<el-dialog
			title="上传版本"
			:visible.sync="open"
			:close-on-click-modal="false"
			:modal-append-to-body="true"
			:append-to-body="true"
			width="50%"
			class="custom-dialog"
			@close="reset"
		>
			<el-form ref="form" :rules="rules" :model="form" label-width="100px">
				<el-row>
					<!-- <el-col :span="12">
						<el-form-item label="版本名称" prop="name">
							<el-input v-model="form.name" placeholder="请输入版本名称" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="版本号" prop="code">
							<el-input
								v-model="form.code"
								type="number"
								placeholder="请输入版本号"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="版本类型" prop="type">
							<el-select v-model="form.type" placeholder="请选择版本类型">
								<el-option
									v-for="dict in [
										{ label: 'java', value: '1' },
										{ label: '后台页面', value: '2' },
									]"
									:key="dict.value"
									:label="dict.label"
									:value="dict.value"
								/>
							</el-select>
						</el-form-item>
					</el-col> -->
					<el-col>
						<el-form-item v-if="open" label="上传升级包">
							<el-upload
								ref="upload"
								class="upload-demo"
								drag
								multiple
								:headers="{
									Authorization: 'Bearer ' + getAccessToken(),
								}"
								:action="`${VUE_APP_BASE_API}/common/uploadToFolder`"
								:on-success="handleOnSuccess"
								:on-error="handleOnError"
								:before-upload="uploadBefore"
							>
								<i class="el-icon-upload" />
								<div class="el-upload__text">
									{{ $t('edition.uploadDrop') }}
									<em>{{ $t('edition.uploadClick') }}</em>
								</div>
								<div
									v-if="form.url"
									slot="tip"
									class="el-upload__tip"
									style="font-size:16px"
								>
									{{ form.fileName }}
									<span v-if="successTitle" style="color:#67C23A;font-size:20px"
										>【{{ successTitle }}】</span
									>
								</div>
								<div
									v-else-if="successTitle"
									slot="tip"
									class="el-upload__tip"
									style="font-size:16px"
								>
									<span style="color:#67C23A;font-size:20px"
										>【{{ successTitle }}】</span
									>
								</div>
							</el-upload>
						</el-form-item>
					</el-col>
					<!-- <el-col :span="24">
						<el-form-item label="版本说明" prop="describes">
							<el-input
								v-model="form.describes"
								type="textarea"
								rows="3"
								placeholder="请输入版本说明"
							/>
						</el-form-item>
					</el-col> -->
				</el-row>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button
					:disabled="!form.url"
					type="primary"
					:loading="saveLoading"
					@click="submitForm"
					>{{ $t('submitText') }}
				</el-button>
				<el-button @click="open = false">{{ $t('cancelText') }}</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import {
	listVersion,
	getVersion,
	delVersion,
	addVersion,
	editVersion,
	exportVersion,
	releaseVersion,
	unZipVersion,
  getJaveVersion
} from '@/api/system/serverVersion'
import { getAccessToken } from '@/data/user'
import JsZip from 'jszip'

export default {
	name: 'Version',
	data() {
		return {
			// 遮罩层
			loading: true,
			successTitle: '',
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 总条数
			total: 0,
			typeOptions: [
				{ label: 'java', value: '1' },
				{ label: '后台页面', value: '2' },
			],
			statusOptions: [
				{ label: '未使用', value: '0' },
				{ label: '已解压', value: '1' },
				{ label: '使用中', value: '2' },
			],
			// 版本表格数据
			versionList: [],
      // 使用中的平台信息
      platformInfo:{},
			// 弹出层标题
			title: '',
			// 是否显示弹出层
			open: false,
			// 日期范围
			dateRange: [],
			// 查询参数
			queryParams: {
				current: 1,
				size: 10,
				name: undefined,
				type: undefined,
				createTime: undefined,
			},
			// 显示搜索条件
			showSearch: true,
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				name: [
					{ required: true, message: '版本名称不能为空', trigger: 'blur' },
				],
				code: [{ required: true, message: '版本号不能为空', trigger: 'blur' }],
				type: [
					{ required: true, message: '版本类型不能为空', trigger: 'blur' },
				],
				appDesc: [
					{ required: true, message: '版本说明不能为空', trigger: 'blur' },
				],
			},
			VUE_APP_BASE_API: process.env.VUE_APP_BASE_API,
			getAccessToken,
		}
	},

	created() {
		this.getList()
		// this.getDicts('server_version_type').then(response => {
		//   this.typeOptions = response.data
		// })
		// this.getDicts('server_version_status').then(response => {
		//   this.statusOptions = response.data
		// })
	},
	methods: {
		// 上传升级包之前
		uploadBefore(file) {
			let haveInfoJson = false
			let zip = new JsZip()
			zip.loadAsync(file).then((zip) => {
				for (let key in zip.files) {
					if (key.includes('info.json')) {
						let base = zip.file(zip.files[key].name).async('blob')
						const reader = new FileReader()
						base.then((res) => {
							let files = new window.File([res], zip.files[key].name, {
								type: 'json',
							})
							reader.readAsText(files, 'UTF-8')
							reader.onload = () => {
								// this.form.name = reader.result.fileName
								// this.form.code = reader.result.version
								// this.form.type = reader.result.type

								Object.assign(this.form, JSON.parse(reader.result))
							}
						})

						haveInfoJson = true
					}
				}
				if (!haveInfoJson) {
					this.$message({
						message: '上传失败,缺少info.json文件',
						type: 'warning',
					})
					return false
				}
			})
		},
		/** 查询版本列表 */
		getList() {
			this.loading = true
      getJaveVersion(this.addDateRange(this.queryParams, this.dateRange)).then((response)=>{
          this.platformInfo.javaV = response.data
      })
			listVersion(this.addDateRange(this.queryParams, this.dateRange)).then(
				(response) => {
					this.versionList = response.data
					this.total = response.total
					this.loading = false
					this.versionList.forEach((item) => {
						if (item.status === '2') {
							if (item.type === '2') {
								// 后台
                this.platformInfo.backstageV = item.code
							} else if (item.type === '1') {
								// java
                // this.platformInfo.javaV = item.code
                this.platformInfo.createTime = item.createTime
                this.platformInfo.updateTime = item.updateTime

							}
						}
					})
				}
			)
		},
		statusFormat(row, column) {
			return this.selectDictLabel(this.statusOptions, row.status)
		},
		typeFormat(row, column) {
			return this.selectDictLabel(this.typeOptions, row.type)
		},
		// 取消按钮
		cancel() {
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				id: undefined,
				code: undefined,
				name: undefined,
				type: undefined,
				status: '0',
				qrcode: undefined,
				url: undefined,
				appDesc: undefined,
				count: undefined,
				deptId: undefined,
				createBy: undefined,
				createTime: undefined,
				delFlag: undefined,
			}
			this.successTitle = ''
			this.resetForm('form')
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.current = 1
			this.getList()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.dateRange = []
			this.resetForm('queryForm')
			this.handleQuery()
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.id)
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},

		/** 新增按钮操作 */
		handleAdd() {
			this.reset()
			this.open = true
			this.title = '添加版本'
			// this.$nextTick(() => {
			//   this.$refs.upload.clearFiles()
			// })
		},
		/** 修改按钮操作 */
		handleEdit(row) {
			this.reset()
			const id = row.id || this.ids
			getVersion(id).then((response) => {
				this.form = response.data
				this.open = true
				this.title = '修改版本'
			})
		},
		/** 提交按钮 */
		submitForm: function() {
			this.$refs['form'].validate((valid) => {
				if (valid) {
					if (this.form.id !== undefined) {
						editVersion(this.form).then((response) => {
							if (response.code === 0) {
								this.msgSuccess('修改成功')
								this.open = false
								this.getList()
							} else {
								this.msgError(response.msg)
							}
						})
					} else {
						addVersion(this.form).then((response) => {
							if (response.code === 0) {
								this.msgSuccess('新增成功')
								this.open = false
								this.getList()
							} else {
								this.msgError(response.msg)
							}
						})
					}
				}
			})
		},
		// 上传成功
		handleOnSuccess(res, rawFile) {
			if (res.code === 1) {
				this.$message({ type: 'error', message: res.msg, showClose: true })
			} else {
				this.successTitle = '上传成功'
				this.form.fileName = res.fileName
				this.form.fileSize = res.fileSize
				this.form.format = res.format
				this.form.url = res.path
			}
		},
		// 上传失败
		handleOnError() {
			this.open = false
			this.$message({ message: '上传失败', type: 'error', showClose: true })
		},
		/** 删除按钮操作 */
		handleDel(row) {
			const ids = row.id || this.ids
			this.$confirm('是否确认删除版本编号为"' + ids + '"的数据项?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function() {
					return delVersion(ids)
				})
				.then(() => {
					this.getList()
					this.msgSuccess('删除成功')
				})
				.catch(function() {})
		},
		/** 导出按钮操作 */
		handleExport() {
			const queryParams = this.queryParams
			this.$confirm('是否确认导出所有版本数据项?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function() {
					return exportVersion(queryParams)
				})
				.then((response) => {
					this.download(response.data)
				})
				.catch(function() {})
		},
		/** 解压 */
		unZip(row) {
			this.$confirm(
				'确认要解压【' + row.name + '】?管理后台解压完手动刷新页面即可',
				'警告',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
				.then(function() {
					return unZipVersion({ id: row.id })
				})
				.then((response) => {
					if (response.code === 0) {
						this.msgSuccess('解压成功')
						this.getList()
					} else {
						this.msgError(response.msg)
					}
				})
				.catch(function() {})
		},

		/** 发布 */
		release(row) {
			this.$confirm(
				'确认要发布【' +
					row.name +
					'】?【温馨提示】出现系统未知错误,请反馈给管理员,说明启动成功需要手动刷新页面',
				'警告',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
				.then(function() {
					return releaseVersion({ id: row.id })
				})
				.then((response) => {
					if (response.code === 0) {
						this.msgSuccess('发布成功')
						this.getList()
					} else {
						this.msgError(response.msg)
					}
				})
				.catch(function() {})
		},
	},
}
</script>

<style lang="scss" scoped>
.app-container {
	height: 100%;
	padding: 10px;
	.container-top {
		display: flex;
		// width: 100%;
		.top-list {
			margin-right: 10px;
			div {
				margin-top: 10px;
				font-weight: 600;
			}
		}
	}
	.custom-dialog {
		.el-select {
			width: 100%;
		}
	}
	.info-table {
		height: 100%;
		width: 100%;
	}
}
</style>
